package com.tg.sieve_data.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tg.sieve_data.annotation.AccessCheck;
import com.tg.sieve_data.common.ResponseResult;
import com.tg.sieve_data.entity.RegionIssue;
import com.tg.sieve_data.entity.TgIssue;
import com.tg.sieve_data.mapper.RegionIssueMapper;
import com.tg.sieve_data.service.TgIssueService;
import com.tg.sieve_data.utils.HttpContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/tgIssue")
public class TgIssueController {
    @Autowired
    private TgIssueService tgIssueService;
    @Autowired
    private RegionIssueMapper regionIssueMapper;

//    @AccessCheck
    @RequestMapping("/getAll")
    public Page<TgIssue> getAll(TgIssue tgIssue,
                                @RequestParam(defaultValue = "1") Integer pageNum,
                                @RequestParam(defaultValue = "10") Integer pageSize) {
        return tgIssueService.getAll(tgIssue,pageNum, pageSize);
    }

    @PostMapping("insert")
    public Object insert(@RequestBody TgIssue tgIssue) {
        tgIssueService.save(tgIssue);
        if (StrUtil.isNotBlank(tgIssue.getRegion())){
            String[] split = tgIssue.getRegion().split(",");
            for (String s : split) {
                RegionIssue regionIssue = new RegionIssue();
                regionIssue.setIssueId(tgIssue.getId());
                regionIssue.setRegionId(Integer.parseInt(s));
                regionIssueMapper.insert(regionIssue);
            }
        }
        return ResponseResult.success("添加成功");
    }
    @GetMapping("delete")
    public Object delete(Integer id ) {
        tgIssueService.removeById(id);
        return ResponseResult.success("删除成功");
    }
    @PostMapping("update")
    public Object update(@RequestBody TgIssue tgIssue) {
        tgIssueService.updateById(tgIssue);
        if (StrUtil.isNotBlank(tgIssue.getRegion())){
            regionIssueMapper.delete(new QueryWrapper<RegionIssue>().eq("issue_id", tgIssue.getId()));
            String[] split = tgIssue.getRegion().split(",");
            for (String s : split) {
                RegionIssue regionIssue = new RegionIssue();
                regionIssue.setIssueId(tgIssue.getId());
                regionIssue.setRegionId(Integer.parseInt(s));
                regionIssueMapper.insert(regionIssue);
            }
        }
        return ResponseResult.success("更新成功");
    }
    @GetMapping("getByIp")
    public List<TgIssue> getByIp(String path) {
        return tgIssueService.getByIp(path);
    }

    @GetMapping("getByRegionId")
    public List<TgIssue> getByRegionId(Integer regionId) {
        return tgIssueService.getByRegionId(regionId);
    }
}
